<template>
	<view>
		<view class="portrait">
			<u-avatar size="150" mode="square" :src="avatarUrl"></u-avatar>
		</view>
		<view class="btn">
			<u-button class="loginButton" :custom-style="btnStyle" :ripple="true" @click="userLogin">
				<u-icon name="weixin-fill" size="48" color="#fff"></u-icon>
				微信用户一键登录
			</u-button>
		</view>
		<Agreement v-model="checked" name="黔顺供销小程序用户隐私协议" :type="agreementType.userPrivacy"/>
	</view>
</template>

<script>
	import {
		wxLogin,
		getUserProfile,
		login
	} from "apis/farmer/user.js"
	import Agreement from "components/agreement"
	import {agreementType} from "utils/enums/agreement"
	/* 导入本地logo */
	import logoUrl from "static/logo.png"
	export default {
		components: {
			Agreement
		},
		data() {
			return {
				avatarUrl: logoUrl,
				checked: [],
				userCode: "",
				agreementType
			}
		},
		computed: {
			btnStyle() {
				return {
					border: '0',
					background: this.checked.length ? '#fc6600' : '#c8c8c8',
					color: '#FFFFFF'
				}
			}
		},
		onLoad() {
			this.wxLogin()
		},
		methods: {
			async wxLogin() {
				this.userCode = await wxLogin()
			},

			async userLogin() {
				if (!this.checked.length) return this.$errorMsg('请阅读并勾选用户协议')
				/* getUserProfile必须通过事件触发 */
				const userData = await getUserProfile()
				const {
					code,
					data,
					msg
				} = await login(this.userCode, userData)

				if (code === 200) {
					this.$successMsg('登录成功')
					this.$store.dispatch("saveToken", data)
					setTimeout(() => {
						if (!data['screenName'] || !data['avatar']) {
							this.pushNewPage("avatar")
						} else {
							this.goback()
						}
					}, 500)
				} else {
					this.$errorMsg(msg)
				}
			}
		},
	}
</script>

<style>
	@import url("login.css");
</style>
